package cn.aylog.dao;

import cn.aylog.pojo.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.lang.reflect.Field;
import java.util.List;

@Repository
public class MoneyDao {

    @Autowired
    private JdbcTemplate template;


    public List<Money> getAll() {
        String sql = "select * from tbl_money";
        List<Money> list = template.query(sql, (RowMapper<Money>) (rs, n) -> {
            Money m = new Money();
            Field[] fields = m.getClass().getDeclaredFields();

            for(Field f : fields) {
                Object object = rs.getObject(f.getName());
                try {
                    f.setAccessible(true);
                    f.set(m, object);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            return m;
        });
        return list;
    }

    public Money getById(Integer id) {
        String sql = "select * from tbl_money";
        Money m = new Money();
        template.query(sql, (RowCallbackHandler) rs -> {
            Field[] fields = m.getClass().getDeclaredFields();

            for(Field f : fields) {
                Object object = rs.getObject(f.getName());
                try {
                    f.setAccessible(true);
                    f.set(m, object);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
        return m;
    }

    public void update(Money m) {
        template.update("update tbl_money set `money`=? where `name`=?", m.getMoney(), m.getName());
    }
}
